var retentHandler = (function() {
    var MAX_PERCENT = 100;
    var chart = null;
    var timeX = [];
    var subtitle = {
        style:{
            color:"#000",
            fontWeight:"bold"
        }
    };
    var transformToDx2 = function(value){
        return Math.round(value*100)/100;
    };
    var getTimeX=function(){
        timeX = [];
        var str='',k='';
        for(var i=0,m=0;m<24;i++){
            if(i==60){
                m++;
                i=00;
            }
            if(i%15==0){
              if(i==0){
                k='0';
              }else{
                k='';
              }
              if(m<10){
                str='0'+m+':'+i+k+':00';
              }else{
                str=m+':'+i+k+':00';
              }
               timeX.push(str);  
            }   
        }
        return timeX;
    };   

    /**
    ** 显示图标
    **/
    var showHighChart = function(currPercArr){
        var clickDetected = false;
            chart = new Highcharts.Chart({
                chart: {
                    renderTo: 'container',
                    animation: false,
                    zoomType: "y"
                },
                
                title: {
                    text: '数据统计图' //标题
                },
                credits: {
                    enabled: false
                },
                xAxis: {
                    categories: timeX //x轴
                },
                yAxis:{
                    max: MAX_PERCENT
                },
                plotOptions: {
                    series: {
                        point: {
                            events: {
                                click: function(e) {
                                    if (clickDetected) {
                                        hasAdjustOk(e, chart, currPercArr);
                                    } else {
                                        clickDetected = true;
                                        setTimeout(function() {
                                            clickDetected = false;
                                        }, 500);
                                    }
                                },
                                drag: function (e) {
                                    // Returning false stops the drag and drops.
                                    var currPointY = transformToDx2(e.y);
                                    var len = currPercArr.length;
                                    var remainPerc = calRemainPerc(e.x, chart.series[0].points);
                                    var hasUsedPerc = transformToDx2(currPointY + remainPerc);
                                    var finalRemainPerc = transformToDx2(MAX_PERCENT - hasUsedPerc);
                                    if(hasUsedPerc >  MAX_PERCENT) {
                                        e.y = transformToDx2(MAX_PERCENT - remainPerc);
                                        subtitle.text = '总共100%，已用100%，剩余0%';
                                        chart.setTitle("数据统计图", subtitle, true);
                                        chart.series[0].data[e.x].update({y: e.y}); 
                                        // currPercArr[e.x] = e.y;
                                        console.log('auto drop: '+e.y);
                                        this.events.drop(e); 
                                        return false;
                                    }else{
                                        e.y = currPointY;
                                        subtitle.text = '总共100%，已用 ' + hasUsedPerc + '%，剩余 ' + finalRemainPerc + '%';
                                        chart.setTitle("数据统计图", subtitle, true);
                                    }
                                    
                                    console.log("x1:" + e.x + " y1:" + e.y + " hasUsedPerc:" + hasUsedPerc + " 剩余 " + finalRemainPerc + "%");
                                    
                                },
                                drop:function (e) {
                                    var rows = $('#tt').datagrid('getRows');
                                    currPercArr[e.x] = transformToDx2(e.y);
                                    updateTable(rows, e.x, e.y, currPercArr);
                                    console.log('drop: '+e.y);
                                }
                            }
                        },
                        stickyTracking: false
                    },
                    column: {
                        stacking: 'normal',                
                        dataLabels: {
                            enabled: true
                        },
                    },
                    line: {
                        cursor: 'ns-resize'
                    }
                },
                tooltip: {
                    yDecimals: 2
                },
                series: [{
                    data:currPercArr,
                    draggableY: true,
                    dragMinY: 0,
                    dragMaxY: MAX_PERCENT
                }]
            });
    };  

    var updateTable = function(rows, index, currPerc, currPercArr){
        var len = rows.length;
        if(typeof(rows[index].currPercent) != "undefined"){
            rows[index].currPercent = transformToDx2(currPerc);
        }else if(typeof(rows[index].currRate) != "undefined"){
            rows[index].currRate = transformToDx2(currPerc);
        }
        for(var i = 0; i< len; i++){
            if(index == 0){
                if(i == index){
                    if(typeof(rows[i].timePercent) != "undefined"){
                        rows[i].timePercent = transformToDx2(currPerc);
                    }else if(typeof(rows[i].totalRate) != "undefined"){
                        rows[i].totalRate = transformToDx2(currPerc);
                    }
                }else{
                    if(typeof(rows[i].timePercent) != "undefined"){
                        rows[i].currPercent = transformToDx2(currPercArr[i]);
                        rows[i].timePercent = transformToDx2(rows[i-1].timePercent + rows[i].currPercent);
                    }else if(typeof(rows[i].totalRate) != "undefined"){
                        rows[i].currRate = transformToDx2(currPercArr[i]);
                        rows[i].totalRate = transformToDx2(rows[i-1].totalRate + rows[i].currRate);
                    }
                }
                
            }else{
                if(i < index){
                    continue;
                }else if(i == index){
                    if(typeof(rows[i].timePercent) != "undefined"){
                        rows[i].timePercent = transformToDx2(rows[i-1].timePercent + currPerc);
                    }else if(typeof(rows[i].totalRate) != "undefined"){
                        rows[i].totalRate = transformToDx2(rows[i-1].totalRate + currPerc);
                    }
                }else if(i > index){
                    if(typeof(rows[i].timePercent) != "undefined"){
                        rows[i].currPercent = transformToDx2(currPercArr[i]);
                        rows[i].timePercent = transformToDx2(rows[i-1].timePercent + rows[i].currPercent);
                    }else if(typeof(rows[i].totalRate) != "undefined"){
                        rows[i].currRate = transformToDx2(currPercArr[i]);
                        rows[i].totalRate = transformToDx2(rows[i-1].totalRate + rows[i].currRate);
                    }
                }
            }
            // console.log(currPercArr[i]);
            // console.log('currPercent:' + currPercArr[i]);
            // console.log(rows[i]);
            $('#tt').datagrid('updateRow',{
                index: i,
                row: rows[i]
            }); 
        } 
    }; 

    var updateChart = function(index, currInputPointY, hasUsedPerc, currPercArr){
        var finalRemainPerc = transformToDx2(MAX_PERCENT - hasUsedPerc);
        subtitle.text = '总共100%，已用 ' + hasUsedPerc + '%，剩余 ' + finalRemainPerc + '%';
        chart.setTitle("数据统计图", subtitle, true);   
        chart.series[0].data[index].update({y: currInputPointY}); 
        currPercArr[index] = currInputPointY; 
    };

    var calRemainPerc = function(pos, points){
        var totallLen = points.length; 
        var remainPerc = 0;
        for(var i= 0; i <totallLen; i++){
            if(pos == i){
                continue;
            }
            remainPerc += transformToDx2(points[i].y);
        }
        return transformToDx2(remainPerc);
    };

    var hasAdjustOk = function(e, chart, currPercArr){
        var currPointY = transformToDx2(e.point.y);
        var remainPerc = calRemainPerc(e.point.x, chart.series[0].points);
        var isAdjustOk = false;
        var maxAdjustRate = transformToDx2(MAX_PERCENT - remainPerc);
        $.messager.prompt('调整单个百分比', '当前的比例是'+currPointY+' ，调整不能超过比例'+maxAdjustRate+'，请输入要调整的比例', function(r){
            if (r){
                var currInputPointY = transformToDx2(r);
                var hasUsedPerc = currInputPointY + remainPerc;
                var dValue = 0;
                if(hasUsedPerc >  MAX_PERCENT){
                    dValue = transformToDx2(MAX_PERCENT - remainPerc);
                    var rows = $('#tt').datagrid('getRows');
                    showProcess(true, '正在更新中...', '正在计算中...');          
                    updateChart(e.point.x, dValue, MAX_PERCENT, currPercArr);
                    updateTable(rows, e.point.x, dValue, currPercArr);
                    showProcess(false);
                    isAdjustOk = false;
                }else{
                    e.point.y = currInputPointY;
                    var rows = $('#tt').datagrid('getRows');
                    showProcess(true, '正在更新中...', '正在计算中...');          
                    updateChart(e.point.x, currInputPointY, hasUsedPerc, currPercArr);
                    updateTable(rows, e.point.x, currInputPointY, currPercArr);
                    showProcess(false);
                    isAdjustOk = true;                                           
                }
            }
        });
        return isAdjustOk;
    };    
    
    return {
        transformToDx2 : transformToDx2,
        getTimeX, getTimeX,
        showHighChart: showHighChart,
        updateTable: updateTable,
        updateChart: updateChart,
        calRemainPerc: calRemainPerc
    };
}());